<template>
  <div class="layout-wrapper">
    <!-- 遮罩层 -->
    <div
        v-if="isMobile && showMobileMenu"
        class="overlay"
        @click="toggleMobileMenu"
    ></div>

    <!-- 侧边栏 -->
    <aside
        :class="[
        'sidebar',
        isMobile
          ? showMobileMenu
            ? 'mobile-show'
            : 'mobile-hide'
          : collapsed
          ? 'collapsed'
          : ''
      ]"
    >
      <div class="menu-header" :class="!collapsed?'':'center'">
        <span v-if="!collapsed || isMobile">🌐 AI大模型平台</span>
        <button v-if="!isMobile" @click="toggleSidebar" class="toggle-btn">
          <div v-if="collapsed">
            <el-icon><Expand /></el-icon>
          </div>
          <div v-else>
            <el-icon><Fold /></el-icon>
          </div>
        </button>


        <button v-if="isMobile" class="close-btn" @click="toggleMobileMenu">
          ×
        </button>
      </div>
      <el-tooltip
          v-if="collapsed"
          class="box-item"
          effect="dark"
          content="新对话"
          placement="bottom"
      >
        <div class="iconBtn" ><el-icon ><ChatSquare /></el-icon></div>
      </el-tooltip>

      <div class="button" @click="startNewChat" v-if="!collapsed || isMobile"><ChatLineSquare class="icon" /> 新对话</div>
      <messageRecord :messageOptions="messageOptions" @removeMessage="handleRemove" @previewData="handlePreviewData"/>
    </aside>

    <!-- 主内容区 -->
    <main class="main-content">
      <header class="top-bar"  v-if="isMobile">
        <button class="menu-btn" @click="toggleMobileMenu">☰</button>
      </header>
      <div class="content-body">
        <messageContent ref="chatRoomRef"
                        @deleteMessage="handleDeleteMessage"
                        @regenerateMessage="handleRegenerateMessage"
                        @setDefaultModel="handleModelChange"
                        @deepThink="handleDeepThink"
                        @uploadFile="handleUploadFile"
                        @webSearchChange="handleWebSearchChange"
                        :messageList="messageList"
                        @sendMessage="handleSendMessage"
                        @startNewChat="handleStartNewChat"
                        @messageUpdate="handleMessageData"/>
      </div>
    </main>
  </div>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount, watch} from 'vue'
import messageRecord from '../../views/components/messageRecord.vue'
import messageContent from '../../views/components/messageContent.vue'
import store from '../../store/index'
import QianWenAPI from '../../utils/qianwen-api.js'
import router from "@/router/index.js";
// 初始化
const qianwen = new QianWenAPI({
  apiKey: 'sk-db1ecd13de3a497fb8e2d0e8971b9992',
  defaultModel: 'qwen3-235b-a22b',
  baseURL:'/qianwen-api'
});

const handleUploadFile = async (file) => {
  const response = await qianwen.uploadFile(file)
  let data = response.fullResponse?.data?.uploaded_files[0]
  chatRoomRef.value.addFile(data)
}

const handleDeleteMessage = (cid,id) => {
  qianwen.deleteMessage(cid,id)
  getHistoryMessages()
}

const handleRegenerateMessage = async (id,aiMessage) => {
  const response = await qianwen.regenerateLastResponse(id)
  chatRoomRef.value.simulateAIResponse(aiMessage,response.response,response.reasoning_content)
}

const handleModelChange = (model) => {
  qianwen.setDefaultModel(model)
}
const handleDeepThink = async (bl) => {
  qianwen.setEnableDeepThought(bl)
}
const handleWebSearchChange = (bl) => {
  qianwen.setEnableSearch(bl)
}
const messageList = ref([])
const handlePreviewData = (id) => {
  const response =  qianwen.getConversation(id);
  messageList.value = response
}
const handleSendMessage = async (content) => {
  console.log(content.files);
  let file = content.files[0]
  if(file?.file_id){
    //`请根据文件(ID: ${file.file_id})回答:`+
    const response = await qianwen.sendMessageStream(content.inputValue,content.options,(text,text2,done)=>{
      chatRoomRef.value.simulateAIResponse(content.aiMessage,text,text2)
      if(done){
        console.log('回答完毕');
      }
    });
  }else{
    const response = await qianwen.sendMessageStream(content.inputValue,content.options,(text,text2,done)=>{
      chatRoomRef.value.simulateAIResponse(content.aiMessage,text,text2)
      if(done){
        console.log('回答完毕');
      }
    });
  }


  getHistoryMessages()
}

const handleStartNewChat = (id) => {
  qianwen.startNewConversation(id)
}

const handleMessageData =async () => {
  getHistoryMessages()
}

const handleRemove = (id) => {
  qianwen.deleteConversation(id)
  getHistoryMessages()
}

/**
 * 将数组按日期分类为对象数组
 * @param {Array} items 包含createdAt属性的对象数组
 * @returns {Array} 包含{date, list}结构的数组
 */
function groupByDateAsArray(items) {
  // 首先创建一个以日期为键的临时对象
  const dateMap = items.reduce((acc, item) => {
    const date = item.createdAt.split('T')[0];
    if (!acc[date]) {
      acc[date] = [];
    }
    acc[date].push(item);
    return acc;
  }, {});

  // 将临时对象转换为所需的数组结构
  return Object.entries(dateMap).map(([date, list]) => ({
    date,
    list
  }));
}
const messageOptions = ref([])


const conversationId = ref(store.state.conversationId)

watch(()=>conversationId, (val) => {
  console.log(val);
  getHistoryMessages()
},{
  deep:true
})
const getHistoryMessages = async() => {

    const r = await qianwen.getConversationList()
    let _tempData = groupByDateAsArray(r)
    _tempData.map(item => {
      return {
        ...item,
        list:item.list.map(ite => {
          return {
            ...ite,
            message:ite.messages.filter(it => it.role === 'user').map(it => {
              return {
                ...it,
                content: it.content.replace(/<[^>]+>/g, '').trim().substring(0, 100)
              }
            })
          }
        })
      }
    })
    messageOptions.value = _tempData
}
getHistoryMessages()

// 开始新对话
const chatRoomRef = ref(null)
const startNewChat = () => {
  chatRoomRef.value.startNewChat()
}

const collapsed = ref(false)
const isMobile = ref(false)
const showMobileMenu = ref(false)

const toggleSidebar = () => {
  collapsed.value = !collapsed.value
}

const toggleMobileMenu = () => {
  showMobileMenu.value = !showMobileMenu.value
}

const checkIsMobile = () => {
  isMobile.value = window.innerWidth <= 768
}

onMounted(() => {
  checkIsMobile()
  window.addEventListener('resize', checkIsMobile)
  // const token = localStorage.getItem('token')
  // if (!token) {
  //   router.push('/login')
  // }
})
onBeforeUnmount(() => {
  window.removeEventListener('resize', checkIsMobile)
})

</script>

<style scoped>
.iconBtn{
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
  cursor: pointer;
}
:root {
  --primary-color: #2979ff; /* 科技蓝 */
  --sidebar-bg: #ffffff;
  --text-color: #222222;
  --hover-color: #f2f7ff;
  --border-color: #e0e0e0;
  --shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.layout-wrapper {
  display: flex;
  height: 100vh;
  overflow: hidden;
  background: #f9f9f9;
}

.overlay {
  position: fixed;
  z-index: 10;
  background: rgba(0, 0, 0, 0.2);
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

/* -------- 侧边栏样式 -------- */
.sidebar {
  width: 240px;
  background: #ffffff;
  border-right: 1px solid var(--border-color);
  padding: 16px 0;
  transition: all 0.3s ease;
  box-shadow: var(--shadow);
  color: var(--text-color);
  box-sizing: border-box;
  z-index: 20;
}
.sidebar.collapsed {
  width: 64px;
}
.sidebar.mobile-hide {
  transform: translateX(-100%);
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 240px;
  background: var(--sidebar-bg);
  transition: transform 0.3s ease;
}
.sidebar.mobile-show {
  transform: translateX(0);
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 240px;
  background: #ffffff;
  transition: transform 0.3s ease;
}

.menu-header {
  font-weight: bold;
  margin-bottom: 24px;
  padding: 0 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.toggle-btn,
.close-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: var(--text-color);
}
/* -------- 主内容样式 -------- */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}
.top-bar {
  height: 60px;
  background: white;
  display: flex;
  align-items: center;
  padding: 0 16px;
  border-bottom: 1px solid var(--border-color);
  box-shadow: var(--shadow);
}
.top-bar .menu-btn {
  font-size: 20px;
  margin-right: 16px;
  background: none;
  border: none;
  cursor: pointer;
}
.content-body {
  flex: 1;
  box-sizing: border-box;
  background: #f9f9f9;
  .title{
    font-size: 18px;
    padding: 8px 16px;
    display: flex;
    justify-content: flex-start;
    background: #ffffff;
    font-weight: bold;
    width: 100%;

    .text{
      width: 60%;
      /*超出一行省略*/
      height: 26px;

      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
*{
  color: #333;
}
.center{
  justify-content: center;
}
.button{
  background: #ffffff;
  border: 1px solid #2979ff;
  color: #2979ff;
  padding: 6px 20px;
  margin: 0 16px;
  border-radius: 4px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: background 0.2s;
  text-align: center;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  .icon{
    margin-right: 4px;
    color: #2979ff;
    width:16px
  }
  &:hover{
    box-shadow:  0 2px 8px rgba(0, 0, 0, 0.05);
    background: #eff3fc;
  }
  &:active{
    box-shadow:  0 2px 8px rgba(0, 0, 0, 0.05);
  }
  &:focus{
    outline: none;
  }

}
</style>
